//
//  RisacDatePicker.swift
//  Risac
//
//  Created by remy on 2018/9/6.
//

import SwiftDate

@objc public protocol RisacDatePickerDelegate: AnyObject {
    @objc optional func datePickerDidSelected(picker: RisacDatePicker, date: Date)
}

open class RisacDatePicker: UIView, ViewLinable {
    public weak var delegate: RisacDatePickerDelegate?
    private var layoutFlag: Bool = false
    private var options: RisacPicker.Options
    public private(set) lazy var picker: UIDatePicker = {
        let picker = UIDatePicker(frame: self.bounds)
        picker.datePickerMode = .date
        picker.addTarget(self, action: #selector(self.valueChanged), for: .valueChanged)
        return picker
    }()
    public var topBar: UIView? {
        didSet {
            oldValue?.removeFromSuperview()
            guard let topBar = topBar else { return }
            self.addSubview(topBar)
            self.triggerLayout()
        }
    }
    
    public init(frame: CGRect, _ closure: ((inout RisacPicker.Options) -> Void)? = nil) {
        var options = RisacPicker.global
        closure?(&options)
        self.options = options
        super.init(frame: frame)
        self.backgroundColor = options.bgColor
        self.addSubview(picker)
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public func triggerLayout() {
        self.layoutFlag = true
        self.setNeedsLayout()
    }
    
    open override func layoutSubviews() {
        super.layoutSubviews()
        guard layoutFlag else { return }
        layoutFlag = false
        var topSpace: CGFloat = 0.0
        if let topBar = topBar { topSpace = topBar.bottom }
        picker.top = topSpace
        picker.height = self.height - topSpace
    }
    
    public func timeString(format: String) -> String {
        return picker.date.toFormat(format)
    }
    
    @objc private func valueChanged() {
        delegate?.datePickerDidSelected?(picker: self, date: picker.date)
    }
}
